<!--资源调度的框架-->
<script setup>
import {ref, reactive, toRefs, computed} from "vue";
import ClusterNamespaceSelector from "./ClusterNamespaceSelector.vue";
import {getSecretListHandler} from "../../api/secret.js";
import {deleteDeploymentHandler as deleteHandler} from "../../api/deployment.js";
import {ElMessage} from "element-plus";
import StringOrMumber from "./StringOrMumber.vue";
import Table from "./Table.vue";
import {object2List,list2Object} from "../../utils/utils.js";
// 导入pinia的数据
import {useItem} from "../../store/index.js";
import {storeToRefs} from "pinia";
import ScheduleConfig from "./scheduling/ScheduleConfig.vue";
import Volume from "./scheduling/Volume.vue";
import Container from "./scheduling/Container.vue";


// 接收类型
const props = defineProps({
    resourceType: {
      type: String,
      default: "Deployment"
    },
    method: {
      type: String,
      default: "Create"
    }
})
// 默认显示
const activeName = ref('basic')
//tabs的表名
const labelActiveName=ref('controllerAnnos')

const useItemer = useItem()
const data = reactive({
  clusterId: "",
  namespace: "",
  item: {
      metadata:{
        name: "",
        labels: {},
        annotations: {},
      },
     spec:{
        selector: {
          metchLabels: {},
        },
        replicas: 1,
        template: {
          metadata: {
            labels: {},
            annotations: {},
          },
          spec: {
            imagePullSecret: [],
            dnsPolicy: 'ClusterFirst',
            hostNetwork: false,
          },
        },
       strategy: {
          type: "RollingUpdate",
         rollingUpdate: {
           maxUnavailable: "25%",
           maxSurge: "25%",
         },
       }
     },
  },
  autoCreateService: false,
  registrySecretList: [],
  dnsPolicyOptions: [
    {
      value: 'ClusterFirst',
      label: 'ClusterFirst'
    },
    {
      value: 'default',
      label: 'default'
    },
    {
      value: 'ClusterFirstWithHostNet',
      label: 'ClusterFirstWithHostNet'
    },
    {
      value: 'None',
      label: 'None'
    }
  ],
  options: {
    controllerAnnoList: [],
    controllerLabelList: [],
    podAnnoList: [],
    podLabelList: [],
    nodeSelectorList: [],
  },
})
const itemRef=ref()
let autoCreateLabel =ref("true")
// 获取registry 类型的secret 方法
// type=kubernetes.io/dockerconfigjson
// labelSelector fieldSelector
const getRegistrySecretList=()=>{
  const getSecretListParas = {
    clusterId: data.clusterId,
    namespace: data.namespace,
    labelSelector: '',
    fieldSelector: 'type=kubernetes.io/dockerconfigjson',
  }

  getSecretListHandler(getSecretListParas).then(
      (res)=>{

          // 数据格式，{name: xxx}
        res.data.data.items.forEach((item)=>{
          data.registrySecretList.push({
            name: item.metadata.name,
          })
        })
        console.log("secretList:",data.registrySecretList)
  })
}
// namespace rollback 回调函数
const namespaceRollback =(clusterId,namespace)=>{
  console.log("namespace changed:",clusterId,namespace)
  data.namespace=namespace;
  data.clusterId=clusterId;
  useItemer.clusterId = clusterId;
  useItemer.namespace = namespace;
  getRegistrySecretList()
}

const  selectChanged =()=>{
  console.log("item:", useItemer.item)
}

// 返回更新方式的类型
const getStrategyType =computed(()=>{
      if(props.resourceType === "Deployment"){
        // RollingUpdate Recreate
        return [
          {
            value: "RollingUpdate",
            label:"滚动更新",
          },
          {
            value: "Recreate",
            label: "先删除后重建",
          },
        ]
      }
})
// 在点击使用宿主机网络按钮时触发事件，提示窗
const hostNetworkChanged =(val)=>{
      console.log('测试宿主机按钮：',val)
   if(val){
     ElMessage({
       message: "开启hostNetwork会直接占用宿主机网络和端口",
       type: "warning",
     })
   }
}
// 变更更新方式
const strategyChange = (val)=> {
  console.log("更新方式：", val)
  // 当更新方式为Recreate的时候，删除rollingUpdate
  if (val === "Recreate") {
    delete useItemer.item.spec.strategy.rollingUpdate
  } else if (val === "RollingUpdate") {
    useItemer.item.spec.strategy.rollingUpdate = {
      maxUnavailable: "25%",
      maxSurge: "25%"
    }
  }
}

// 点击更新或创建
const submit=()=>{
  console.log("data.items:",useItemer.item)
  let obj = {}
  let controllerAnnosObj = {}
  let controllerLablelsObj = {}
  let podAnnosObj = {}
  let podLablelsObj = {}
  // 数据的二次处理
  // 1. 把list转成object
  if (autoCreateLabel.value === "true"){
      //说明是自动生成lable
    obj = {
        app: useItemer.item.metadata.name,
      }
    controllerAnnosObj=obj
    controllerLablelsObj=obj
    podAnnosObj=obj
    podLablelsObj=obj
  }else {
     controllerAnnosObj=list2Object(data.options.controllerLabelList)
     controllerLablelsObj=list2Object(data.options.controllerLabelList)
     podAnnosObj=list2Object(data.options.podAnnoList)
     podLablelsObj=list2Object(data.options.podLabelList)
  }
    useItemer.item.metadata.labels = controllerLablelsObj
    useItemer.item.metadata.annotations = controllerAnnosObj
    useItemer.item.spec.template.metadata.labels = podLablelsObj
    useItemer.item.spec.template.metadata.annotations = podAnnosObj
    useItemer.item.spec.selector.metchLabels = podLablelsObj

    // 处理NodeSelector
    useItemer.item.spec.template.spec.nodeSelector = list2Object(data.options.nodeSelectorList)
}


const {registrySecretList,dnsPolicyOptions,autoCreateService,options}= toRefs(data)
const {item} = storeToRefs(useItem())



</script>

<template>
  <el-card >
    <!-- 创建资源的表单   -->
    <el-form
        :model="item"
        ref="itemRef"
        label-width="140px"

    >
      <!-- 外层tabs   -->
      <el-tabs v-model="activeName" class="demo-tabs" >
        <el-tab-pane label="基本配置" name="basic" class="tab-pane" >
          <el-card class="box-card">
            <template #header>
              <div class="auto-space-between">
                <!--namespace 和 cluster 选择器-->
                <div>
                  <ClusterNamespaceSelector
                      @namespaceChangedRollback="namespaceRollback"
                  ></ClusterNamespaceSelector>
                </div>
                <div></div>
              </div>
            </template>
            <div>
              <!--基本配置-->
              <!-- 名称 副本 密码 dns策略 -->
              <el-row :gutter="20">
                <!-- 名称 -->
                <el-col :span="6">
                  <el-form-item label="名称" prop="metadata.name" required>
                    <el-input  v-model.trim="item.metadata.name" style="width: 180px" placeholder="请输入资源名称"/>
                  </el-form-item>
                </el-col>
                <!-- 副本数 -->
                <el-col :span="6">
                  <el-form-item label="副本数" prop="spec.replicas">
                    <el-input-number v-model="item.spec.replicas" :min="0" :max="100"/>
                  </el-form-item>
                </el-col>
                <!-- 私有镜像仓库密钥 -->
                <el-col :span="6">
                  <el-form-item label="私有仓库密钥" prop="spec.replicas">
                    <el-select v-model="item.spec.template.spec.imagePullSecret" multiple collapse-tags  value-key="name" placeholder="绑定仓库密码">
                      <el-option
                          v-for="s in registrySecretList"
                          :key="s.name"
                          :label="s.name"
                          :value="s"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- dns策略 -->
                <el-col :span="6">
                  <el-form-item label="dns策略" prop="spec.dnsPolicy">
                    <el-select v-model="item.spec.template.spec.dnsPolicy" placeholder="dns策略">
                      <el-option
                          v-for="s in dnsPolicyOptions"
                          :key="s.value"
                          :label="s.label"
                          :value="s.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <!--基本配置-->
              <!-- 更新方式 hostNetwork-->
              <el-row :gutter="20">
                <!-- dns策略 -->
                <el-col :span="6">
                  <el-form-item label="更新方式" prop="spec.strategy.type">
                    <el-select v-model="item.spec.strategy.type" placeholder="请选择更新方式" @change="strategyChange">
                      <el-option
                          v-for="s in getStrategyType"
                          :key="s.value"
                          :label="s.label"
                          :value="s.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="最大不可用" prop="" v-if="item.spec.strategy.type === 'RollingUpdate'">
                    <!--                  <el-input  v-model.trim="item.spec.strategy.rollingUpdate.maxUnavailable" style="width: 64px"/>-->
                    <StringOrMumber v-model:data="item.spec.strategy.rollingUpdate.maxUnavailable"  placeholder="最大不可用"></StringOrMumber>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="可超出最大值" prop="" v-if="item.spec.strategy.type === 'RollingUpdate'">
                    <!--                  <el-input  v-model.trim="item.spec.strategy.rollingUpdate.maxSurge" style="width: 64px"/>-->
                    <StringOrMumber v-model:data="item.spec.strategy.rollingUpdate.maxSurge"  placeholder="可超出最大值"></StringOrMumber>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="使用宿主机网络">
                    <el-switch
                        v-model="item.spec.template.spec.hostNetwork"
                        class="ml-2"
                        style="--el-switch-on-color: #ff4949"
                        @change="hostNetworkChanged"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 标签配置 自动添加service -->
              <el-row :gutter="20">
                <!-- 标签配置 -->
                <el-col :span="6">
                  <el-form-item label="标签及注释" prop="">
                      <el-radio-group v-model="autoCreateLabel" class="ml-4">
                        <el-radio label="true" size="large">自动生成</el-radio>
                        <el-radio label="false" size="large">手动配置</el-radio>
                      </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="自动添加service">
                    <el-switch
                        v-model="autoCreateService"
                        class="ml-2"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>
          <!-- 标签配置 -->
          <el-card v-if="autoCreateLabel === 'false'" style="margin-top: 20px">
              <el-tabs tab-position="left"  v-model="labelActiveName" class="demo-tabs" >
                <el-tab-pane label="控制器注释" name="controllerAnnos">
                  <Table :list="options.controllerAnnoList"></Table>
                </el-tab-pane>
                <el-tab-pane label="控制器的标签" name="controllerLabels">
                  <Table :list="options.controllerLabelList" ></Table>
                </el-tab-pane>
                <el-tab-pane label="Pod注释" name="podAnnos">
                  <Table :list="options.podAnnoList" ></Table>
                </el-tab-pane>
                <el-tab-pane label="Pod标签" name="podLabels">
                  <Table :list="options.podLabelList" ></Table>
                </el-tab-pane>
              </el-tabs>
          </el-card>
        </el-tab-pane>
        <!--  节点选择器      -->
        <el-tab-pane label="调度配置" name="affinity" class="tab-pane">
          <ScheduleConfig :list="options.nodeSelectorList"></ScheduleConfig>
        </el-tab-pane>
        <el-tab-pane label="存储卷配置" name="volume" class="tab-pane" >
            <Volume></Volume>
        </el-tab-pane>
        <el-tab-pane label="容器配置" name="container" class="tab-pane" >
          <Container container-type="container"></Container>
        </el-tab-pane>
        <el-tab-pane label="初始化容器" name="init-container" class="tab-pane" >
          <Container container-type="init"></Container>
        </el-tab-pane>
      </el-tabs>
        <span style="display: block;margin-top: 30px"  class="dialog-footer">
        <el-button @click="clear()">Yaml</el-button>
        <el-button type="primary" @click="submit()" >
          {{ props.method === "Create"?"创建":"更新" }}
        </el-button>
      </span>
    </el-form>
  </el-card>
  <el-card class="box-card">
  </el-card>
</template>

<style scoped>
.tab-pane {
  height: 600px;
}
</style>